package com.yxm.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: yxm
 * @Date: 2021/1/6 18:13
 * @Emial: yxm1136656235@163.com
 * @Description:  自定义负载均衡策略
 */
public class YxmRandomRule extends AbstractLoadBalancerRule {

    private int total = 0;          //被调用的次数 方便计算被调用了多少次
    private int currentIndex = 0;   //当前是谁在提供服务


//    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {         //线程中断
                return null;
            }
            List<Server> upList = lb.getReachableServers();         //获取正常的服务
            List<Server> allList = lb.getAllServers();      //获取全部服务

            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }

            //=======================原来的===========================
            int index = chooseRandomInt(serverCount);       //生成区间随机数
            server = upList.get(index); //从活着的服务中，随机获取一个
            //=======================原来的===========================

            /**
             * 自定义算法  每个服务调取5次后，重新下一个服务5次，轮询  有bug 算法问题
             */
            //=========================现在的=========================
            /*if (total < 5){
                 server = upList.get(currentIndex);
                 currentIndex++;
            }else{
                total = 0;
                currentIndex++;
                if (currentIndex > upList.size()){
                    currentIndex = 0;
                }
               server = upList.get(currentIndex);      //从活着的服务中，获取指定的服务来进行操作
            }*/
            //=========================现在的=========================

            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }
            server = null;
            Thread.yield();
        }

        return server;

    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // TODO Auto-generated method stub

    }
}
